package com.lagou.Filter;

import com.lagou.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;

@WebFilter(filterName = "LoginFilter" ,urlPatterns = {"/mainPage.jsp",
"/manageClassGrade.jsp", "/manageStudent.jsp"})
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1、实现对用户访问主页面的过滤操作，也就是只有用户登录后才能访问主页面，否则一律拦截
        HttpServletRequest httpServletRequest = (HttpServletRequest)req;

        //2、判断session中是否已有用户名信息，若有则放行，若没有则判断cookie中是否有，若有则放行，否则进行阻拦
        //2.1 session中是否已有用户名信息
        HttpSession session = httpServletRequest.getSession();
        User user = (User)session.getAttribute("user");
        System.out.println("过滤器中 user="+user);
        //获取Servlet的请求路径
        String servletPath = httpServletRequest.getServletPath();
        String userName = null;
        if (null != user && servletPath.contains("adminLoginServlet")) {
            chain.doFilter(req, resp);
        } else {
            //2.2若没有登录，则查询cookie中是否已经保存账号和密码信息
            Cookie[]cookies = httpServletRequest.getCookies();
            System.out.println("数组中： "+ Arrays.toString(cookies));
            if(cookies != null && cookies.length>0){
                for (Cookie cookie: cookies){
                    String name = cookie.getName();
                    System.out.println("过滤器中： name="+name);
                    if("userName".equals(name)){
                        userName = name;
                        break;
                    }
                }
            }
            if(null!= userName){
                chain.doFilter(req,resp);
            }else {
                req.getRequestDispatcher("index.jsp").forward(req, resp);
            }
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
